<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { FieldValues } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { useAfterSaleProcess, useConfirmGoods, useConfirmShipping, useGetAfterSaleList } from '@fl/api/city-service'
import { SearchForm, SearchTable } from '@fl/components'
import { useLocaleStore } from '@fl/store/modules/locale'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import { afterSaleFlowStatus, afterSaleReason, afterSaleType, approvedStatus, bothStatus, orderStatus, returnStateId, shippingType, titleObj } from './type'

const router = useRouter()
const localeStore = useLocaleStore()

const initialState = {
    afterSaleType: undefined, // 售后类型
    like: undefined, // 商品名称
    orderCode: undefined, // 订单号
    status: undefined,
}

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const state = ref<FieldValues>(cloneDeep(initialState))
const tablePage = ref(cloneDeep(initialPage))
const list = ref([])
const columns = [
    {
        label: '订单号：',
        prop: 'orderCode',
    },
    {
        label: '商品名称：',
        prop: 'like',
    },

    {
        label: '售后类型：',
        options: [
            {
                label: '仅退款',
                value: '0',
            },
            {
                label: '仅换货',
                value: '1',
            },
            {
                label: '退货退款',
                value: '2',
            },
        ],
        prop: 'afterSaleType',
        valueType: 'select',
    },
    {
        label: '售后状态：',
        options: [
            {
                label: '售后成功/拒绝售后',
                value: '1',
            },
            {
                label: '商家待处理',
                value: '2',
            },
            {
                label: '待商家收货',
                value: '3',
            },
            {
                label: '待商家发货',
                value: '4',
            },
            {
                label: '待买家发货',
                value: '5',
            },
            {
                label: '待买家收货',
                value: '6',
            },
            {
                label: '上门中',
                value: '7',
            },
            {
                label: '退款中',
                value: '8',
            },
            {
                label: '退款成功',
                value: '9',
            },
        ],
        prop: 'status',
        valueType: 'select',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'orderCode', title: '订单号' },
        { field: 'merchantInfor', slots: { default: 'merchantInfor' }, title: '商品信息', width: 200 },
        { field: 'orderPaidAmount', title: '金额（￥）' },
        { field: 'orderStatus', slots: { default: 'orderStatus' }, title: '订单状态' },
        { field: 'afterSaleType', slots: { default: 'afterSaleType' }, title: '售后类型' },
        { field: 'afterSaleReason', slots: { default: 'afterSaleReason' }, title: '售后原因', width: 170 },
        { field: 'createTime', title: '申请时间', width: 150 },
        { field: 'afterSaleFlowStatus', slots: { default: 'afterSaleFlowStatus' }, title: '状态' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 150 },
    ],
})
const dialogTitle = ref('确认发货')
const dialogVisible = ref(false)
const dialogFormRef = ref()
const approvedData = ref({
    orderLineId: '',
})
const rules = {
    orderTrackingNumber: [
        { message: '请输入快递单号', required: true, trigger: 'blur' },
    ],
}
const detailData = ref({
    afterSaleCode: '',
    afterSaleId: '',
    companyName: '',
    orderCode: '',
    orderId: '',
    orderLineId: '',
    orderTrackingNumber: '',
})

const params = computed(() => ({
    ...state.value,
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))

const { data, isLoading } = useGetAfterSaleList(params)

const { isPending: shippingLoading, mutate: mutateShipping } = useConfirmShipping()

const { isPending: goodsLoading, mutate: mutateGoods } = useConfirmGoods()
const { mutate: mutateProcess } = useAfterSaleProcess()

watchEffect(() => {
    if (data.value) {
        list.value = data.value?.records || []
        tablePage.value.total = data.value?.total || 0
    }
})

onBeforeMount(() => {
    localeStore.setCurrentPage(Number(1))
})

onBeforeUnmount(() => {
    localeStore.setCurrentPage(Number(1))
})

/**
 * methods start
 */
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function submitSearch(values) {
    state.value = cloneDeep(values)
    tablePage.value.currentPage = 1
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}

function toDetail(row) {
    router.push({ name: 'afterSales-detail', params: { id: row.orderLineId } })
}

function confirmShipment(row) {
    const { afterSaleCode, afterSaleId, orderCode, orderId, orderLineId } = row
    dialogTitle.value = titleObj.COMFIRMSHIPMENT
    detailData.value = {
        afterSaleCode,
        afterSaleId,
        companyName: '',
        orderCode,
        orderId,
        orderLineId,
        orderTrackingNumber: '',
    }
    dialogVisible.value = true
}

// 确认发货
function shipmentSubmit(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    formEl.validate(async (valid) => {
        if (valid) {
            const { afterSaleCode, afterSaleId, companyName, orderCode, orderId, orderLineId, orderTrackingNumber } = detailData.value
            mutateShipping({
                afterSaleCode,
                afterSaleId,
                companyName,
                orderCode,
                orderId,
                orderLineId,
                orderTrackingNumber,
            }, {
                onSuccess: () => {
                    dialogVisible.value = false
                    ElMessage.success('操作成功')
                },
            })
        }
    })
}

// 确认收货
function confirmReceive(row) {
    const { orderLineId } = row
    ElMessageBox.confirm(
        '是否确认进行售后收货',
        '确认收货',
    ).then(() => {
        mutateGoods({
            orderLineId,
        })
    }).catch(() => {
        ElMessage({
            message: '取消收货',
            type: 'info',
        })
    })
}
// 审核
function approvedHolder(row) {
    // 这里如果用ElMessageBox.confirm区分不了点击关闭图标和点击取消（拒绝按钮）
    dialogTitle.value = titleObj.APPROVED
    approvedData.value.orderLineId = row.orderLineId
    dialogVisible.value = true
}

// 提交审核
function confimApproved(status) {
    mutateProcess({
        orderLineId: approvedData.value.orderLineId,
        status, // 0：拒绝，1：通过,
    }, {
        onSuccess: () => {
            dialogVisible.value = false
            ElMessage.success('操作成功')
        },
    })
}

function toPage(row) {
    router.push({ name: 'commodity-detail', params: { id: row.spuId, pageType: 'detail' } })
}

/**
 * methods end
 */
</script>

<template>
    <div class="after-sales-management">
        <ElCard class="mb-20"
                shadow="never"
        >
            <SearchForm v-bind="state"
                        :columns="columns"
                        submit-text="搜索"
                        @reset="resetSearch"
                        @submit="submitSearch"
            />
        </ElCard>

        <ElCard shadow="never">
            <SearchTable v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :loading="isLoading"
                         :data="list"
                         @page-change="handlePageChange"
            >
                <template #merchantInfor="{ row }">
                    <div class="merchant-info">
                        <div class="img-box"
                             :style="{ backgroundImage: `url(${row.skuImgPath})` }"
                        >
                            图片
                        </div>

                        <el-button type="primary"
                                   text
                                   @click="toPage(row)"
                        >
                            {{ row.skuName }}
                        </el-button>
                    </div>
                </template>

                <template #orderStatus="{ row }">
                    {{ orderStatus[row.orderStatus] }}
                </template>

                <template #afterSaleType="{ row }">
                    {{ afterSaleType[row.afterSaleType] }}
                </template>

                <template #afterSaleReason="{ row }">
                    {{ afterSaleReason[row.afterSaleReason] }}
                </template>

                <template #afterSaleFlowStatus="{ row }">
                    {{ row.spuDelivery === shippingType.FLASH_DELIVERY ? afterSaleFlowStatus[row.afterSaleFlowStatus] : returnStateId[row.returnStateId] }}
                </template>

                <template #operate="{ row }">
                    <div class="operate-btns">
                        <!-- 以下三个条件或的关系，满足一条就是true -->

                        <!-- 闪送模式：订单状态为待收货或已完成状态且售后状态为商家处理 (row.spuDelivery === shippingType.FLASH_DELIVERY可以不判断为了考虑可读性) -->
                        <!-- 快递模式： 订单状态为待收货或已完成状态且售后状态为商家待处理 (row.spuDelivery === shippingType.EXPRESS可以不判断为了考虑可读性)  -->
                        <!-- 售后类型为仅退款且订单状态为待发货且商家处理（闪送）或商家待处理（快递）  -->
                        <el-button v-if="(row.spuDelivery === shippingType.FLASH_DELIVERY && (row.orderStatus === bothStatus.daishouhuo || row.orderStatus === bothStatus.yiwancheng) && row.afterSaleFlowStatus === bothStatus.shangjiachuli) || (row.spuDelivery === shippingType.EXPRESS && (row.orderStatus === bothStatus.daishouhuo || row.orderStatus === bothStatus.yiwancheng) && row.returnStateId === bothStatus.shangjiadaichuli) || (row.afterSaleType === bothStatus.jintuikuan && row.orderStatus === bothStatus.daifahuo && ((row.spuDelivery === shippingType.FLASH_DELIVERY && row.afterSaleFlowStatus === bothStatus.shangjiachuli) || (row.spuDelivery === shippingType.EXPRESS && row.returnStateId === bothStatus.shangjiadaichuli)))"
                                   type="primary"
                                   text
                                   @click="approvedHolder(row)"
                        >
                            审核
                        </el-button>
                        <!-- 闪送模式：售后状态为商家收货 -->
                        <!-- 快递模式：售后状态为待商家收货 -->
                        <el-button v-if="(row.spuDelivery === shippingType.FLASH_DELIVERY && row.afterSaleFlowStatus === bothStatus.shangjiashouhuo) || (row.spuDelivery === shippingType.EXPRESS && row.returnStateId === bothStatus.daishangjiashouhuo)"
                                   type="primary"
                                   text
                                   :loading="goodsLoading"
                                   @click="confirmReceive(row)"
                        >
                            确认收货
                        </el-button>
                        <!-- 闪送模式：无 -->
                        <!-- 快递模式：售后状态为商家待发货 -->
                        <el-button v-if="row.spuDelivery === shippingType.EXPRESS && row.returnStateId === bothStatus.shangjiadaifahuo"
                                   type="primary"
                                   text
                                   @click="confirmShipment(row)"
                        >
                            确认发货
                        </el-button>
                        <!-- 闪送模式：售后状态为退款成功 -->
                        <!-- 快递模式：售后状态为退款成功或售后成功 -->
                        <el-button v-if="(row.spuDelivery === shippingType.FLASH_DELIVERY && row.afterSaleFlowStatus === bothStatus.shan_tuikuanchenggong) || (row.spuDelivery === shippingType.EXPRESS && (row.returnStateId === bothStatus.tuikuanchenggong || row.returnStateId === bothStatus.shouhouchenggong))"
                                   type="primary"
                                   text
                        >
                            退款详情
                        </el-button>

                        <el-button type="primary"
                                   text
                                   @click="toDetail(row)"
                        >
                            查看
                        </el-button>
                    </div>
                </template>
            </SearchTable>
        </ElCard>

        <el-dialog v-model="dialogVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   :title="dialogTitle"
                   width="666"
                   :class="dialogTitle === titleObj.APPROVED ? 'approved-dialog' : ''"
        >
            <template v-if="dialogTitle === titleObj.COMFIRMSHIPMENT">
                <div class="dialog-content">
                    <el-form ref="dialogFormRef"
                             style="max-width: 600px"
                             :model="detailData"
                             :rules="rules"
                             label-width="auto"
                             class="dialog-form"
                    >
                        <el-form-item label="订单编号：">
                            <el-input v-model="detailData.orderCode"
                                      disabled
                            />
                        </el-form-item>

                        <el-form-item label="售后编号：">
                            <el-input v-model="detailData.afterSaleCode"
                                      disabled
                            />
                        </el-form-item>

                        <el-form-item label="快递品牌：">
                            <el-input v-model="detailData.companyName" />
                        </el-form-item>

                        <el-form-item label="快递单号："
                                      prop="orderTrackingNumber"
                        >
                            <el-input v-model="detailData.orderTrackingNumber" />
                        </el-form-item>
                    </el-form>
                </div>
            </template>

            <template #footer>
                <div class="dialog-footer">
                    <el-button v-if=" dialogTitle === titleObj.COMFIRMSHIPMENT"
                               type="primary"
                               :loading="shippingLoading"
                               @click="shipmentSubmit(dialogFormRef)"
                    >
                        确认发货
                    </el-button>

                    <el-button v-if=" dialogTitle === titleObj.APPROVED"
                               type="info"
                               :loading="shippingLoading"
                               size="large"
                               class="reject-btn"
                               @click="confimApproved(approvedStatus.REJECT)"
                    >
                        拒 绝
                    </el-button>

                    <el-button v-if=" dialogTitle === titleObj.APPROVED"
                               type="primary"
                               :loading="shippingLoading"
                               size="large"
                               @click="confimApproved(approvedStatus.PASS)"
                    >
                        通 过
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.merchant-info {
    display: flex;
    align-items: center;
    .img-box {
        width: 50px;
        height: 50px;
        background-size: 100% 100%;
        color: rgba(255, 255, 255, 0);
        margin-top: 12px;
    }
    > .name {
        padding-left: 6px;
    }
}
.operate-btns {
    :deep(.el-button) {
        margin: 0;
        padding: 6px;
    }
}
.dialog-footer {
    display: flex;
    justify-content: center;
}
:deep(.approved-dialog) {
    .el-dialog__body {
        display: none;
    }
    .el-dialog__footer {
        border: 0;
    }
}
.approved-dialog {
    .reject-btn {
        margin-right: 36px;
    }
}
</style>
